/*
 * @Author: tian_biao
 * @Date: 2021-08-04 14:33:41
 * @LastEditTime: 2021-08-04 15:26:26
 * @Description: 
 */
import { Toast } from 'vant'
import $ from './jquery.min-2.1.4'
var zzNewRfid = {
    loadingMessage: function (msg) {
        //loading提示
        Toast.loading({
            duration: 0,
            message: msg,
            forbidClick: true,
            overlay: true
        })
    },
    flag: true,
    /*
     *初始化设备
     * */
    init: function (success) {
        window.setTimeout(function () {
            RfidImpl2.init("init", function (data) {
                success(data)
            }, function (error) {
                console.log(JSON.stringify(error))
                Toast.clear();
                // Dialog.showInfo("初始化手持智芯设备失败。", 1, {
                // 	prompts: "提示",
                // 	confirmTxt: "确认",
                // 	cancel: "取消"
                // }, null, null, true);
                Dialog.confirm({
                    title: '提示',
                    message: '初始化手持智芯设备失败。',
                })
                    .then(() => {
                        // on confirm
                    })
                    .catch(() => {
                        // on cancel
                    });
            })
        }, 500)
    },

    /*
    *连接蓝牙
    * */
    open: function (success) {
        zzNewRfid.init(function () {
            setTimeout(function () {
                RfidImpl2.open('', function (a, b) {
                    success()
                    console.log("打开设备")
                }, function (error) {
                    console.log(JSON.stringify(error))
                    Toast.clear();
                    // Dialog.showInfo("蓝牙连接失败。", 1, {
                    // 	prompts: "提示",
                    // 	confirmTxt: "确认",
                    // 	cancel: "取消"
                    // }, null, null, true);
                    Dialog.confirm({
                        title: '提示',
                        message: '蓝牙连接失败。',
                    })
                        .then(() => {
                            // on confirm
                        })
                        .catch(() => {
                            // on cancel
                        });
                })
            }, 30)
        })
    },

    /*
    *断开蓝牙
    * */
    close: function (success) {
        RfidImpl2.close('', function (data) {
            success()
            console.log("关闭设备" + JSON.stringify(data))
        }, function (error) {
            console.log(JSON.stringify(error))
        })
    },
    searchTagRfid() {
        // var dtd = $.Deferred();
        RfidImpl2.searchTag('', function (data) {
            dtd.resolve(data)
        }, function (error) {
            dtd.reject(error)
        })
        return promise()
    },

    /*
    *开始盘点
    * */
    searchTag: function (success, failed) {
        zzNewRfid.flag = true
        var dingshi = window.setTimeout(function () {
            if (zzNewRfid.flag) {
                Toast.clear();
                zzNewRfid.stopSearch(function () { })
                Dialog.confirm({
                    title: '提示',
                    message: '搜索不到可用设备。',
                })
                    .then(() => {
                        // on confirm
                    })
                    .catch(() => {
                        // on cancel
                    });
            }
        }, 30000)

        zzNewRfid.searchTagRfid().then(function (data) {
            zzNewRfid.flag = false
            clearTimeout(dingshi)
            var rfidStatus = {
                rfid2: true
            }
            rfidStatus = JSON.stringify(rfidStatus)
            sessionStorage.setItem("rfidStatus", rfidStatus)
            console.log(JSON.stringify(data))
            zzNewRfid.stopSearch(function () {
                console.log("标签")
                var param = JSON.parse(data)
                if (!!param && !!param[0]) {
                    sessionStorage.removeItem("rfidStatus")
                    success(param)
                } else {
                    Toast.clear();
                    if (failed) {
                        failed()
                    }
                    Dialog.confirm({
                        title: '提示',
                        message: '搜索RFID失败，请重试。',
                    })
                        .then(() => {
                            // on confirm
                        })
                        .catch(() => {
                            // on cancel
                        });
                }
            })
        }, function (error) {
            Toast.clear();
            clearTimeout(dingshi);
            // 跳转页面   后面改成vue
            // Require('model/homepage/js/rifdDeviceChoose').initialize("#ptmo-index");
            // Dialog.showInfo("请检查是否连接智芯设备。", 1, {
            //     prompts: "提示",
            //     confirmTxt: "确认",
            //     cancel: "取消"
            // }, null, null, true);
        })
    },

    /*
    *停止盘点
    * */
    stopSearch: function (success) {
        RfidImpl2.stopSearch('', function (data) {
            success()
            console.log("停止盘点" + JSON.stringify(data))
        }, function (error) {
            console.log("111111" + JSON.stringify(error))
        })
    },

    /*
    * 只返回rfid
    */
    searchRfid: function (success, fail) {
        zzNewRfid.loadingMessage("正在搜索可用设备...")
        zzNewRfid.searchTag(function (data) {
            //单次搜索完停止搜索
            Toast.clear();
            var rfid = ''
            if (!data) {
                fail()
            } else {
                if (data.length == 0) {
                    success(rfid)
                } else {
                    data.map(function (item) {
                        if (item.indexOf("-") > 0) {
                            var arr = item.split("-")
                            item = arr[1]
                        }
                    })
                    success(data[0])

                    //记录扫描二维码
                    // 已废弃
                    // recordRfidOrQrcode.record([data[0]], 'RFID')
                }
            }
        }, function () {
            fail()
        })
    },
    /**
     * 单次搜索
     */
    searchOnce: function (success, fail) {
        zzNewRfid.loadingMessage("正在搜索可用设备...")
        zzNewRfid.searchTag(function (data) {
            //单次搜索完停止搜索
            if (data.length == 0) {
                Toast.clear();
                Dialog.confirm({
                    title: '提示',
                    message: '搜索不到可用设备。',
                })
                    .then(() => {
                        // on confirm
                    })
                    .catch(() => {
                        // on cancel
                    });
            } else {
                console.log(JSON.stringify(data))
                zzNewRfid.getDevices(data, function (result) {
                    success(result)
                }, function () {
                    if (!!fail) {
                        fail()
                    }
                })
            }
        }, function () {
            if (!!fail) {
                fail()
            }
        })
    },
    /**
    * 盘点模式
    */
    continueSearch: function (success, fail) {
        zzNewRfid.searchTag(function (data) {
            //单次搜索完停止搜索
            Toast.clear();

            if (!data) {
                fail()
                return false;
            }

            if (!!data && data.length == 0) {
                Toast.clear();
                console.log("搜索不到可用设备。")
                // Dialog.showInfo("搜索不到可用设备。", 1, {
                // 	prompts: "提示",
                // 	confirmTxt: "确认",
                // 	cancel: "取消"
                // }, null, null, true);
            } else {
                //    涉及缓存  暂时不用
                //    console.log("盘点1" + JSON.stringify(data))
                //    zzNewRfid.getDevices(data, function (result) {
                //        console.log("盘点" + JSON.stringify(result))
                //        success(result)
                //    }, function () {
                //        fail()
                //    })
            }
        }, function () {
            fail()
        })
    },
    /**
    * 查询设备列表
    */
    getDevices: function (tagIds, success, fail) {
        var devices = [];
        var sql = "SELECT DEVICE_ID, DEVICE_NAME, DEVICE_TYPE_ID, UNIT_ID, SUBSTATION_ID, PARENT_ID, RFID FROM T_DEVICE WHERE RFID in ('"

        var parmars = '';

        tagIds.map(function (item) {
            if (item.indexOf("-") > 0) {
                var arr = item.split("-")
                item = arr[1]
            }
        })

        //			if (tagIds.length == 1) {
        //				parmars = "RFID = '" + tagIds[0] + "'"
        //			} else {
        //				parmars = parmars.join(",")				
        //				tagIds.reduce(function(pre, cur) {
        //					parmars += "RFID = '" + pre + "' OR RFID = '" + cur.toString() + "'"
        //				})
        //			}
        parmars = tagIds.join("','")

        //记录扫描二维码
        // 已废弃
        // recordRfidOrQrcode.record(tagIds, 'RFID')

        DbUtil.execOneSql(sql + parmars + "')", [], function (tx, result) {
            for (var i = 0; i < result.rows.length; i++) {
                var rowObj = result.rows.item(i);

                tagIds.map(function (item, index) {
                    if (rowObj.RFID == item) {
                        devices.push(rowObj)
                    }
                })
            }

            zzNewRfid.chooseDevice(devices, function (item) {
                success(item)
            }, function () {
                fail()
            })
        })
    },
    //根据设备数量选择设备
    chooseDevice: function (devices, success, fail) {
        Toast.clear();
        if (devices.length == 0) {
            //未搜索到设备，提示跳转下载变电站数据
            // Dialog.showInfo("未扫描到当前变电站中的设备！", 1, {
            //     prompts: "提示",
            //     confirmTxt: "确认",
            //     cancel: "取消"
            // }, function () { }, null, true);
            Dialog.confirm({
                title: '提示',
                message: '未扫描到当前变电站中的设备！',
            })
                .then(() => {
                    // on confirm
                })
                .catch(() => {
                    // on cancel
                });
            fail()
        } else if (devices.length == 1) {
            //直接返回设备
            success(devices[0])
        } else {
            //多个设备，弹框选择
            zzNewRfid.devicesDialog(devices, function (data) {
                success(data)
            })
        }
    },
    //多个设备弹框
    devicesDialog: function (devices, success) {
        var deviceIndex = ''
        var contentBefor = `
			<div id='rfidDevices'>
				<div class="mark">
					<div class="commonIdCenter">
						<div class="heder">
							<span>请选择设备</span>
						</div>

						<div class="bottom-content">
							<ul class="mainContent">`

        var contentList = ``
        devices.map(function (item, index) {
            contentList += "<li class='rfidList' data-index=" + index + ">" + item.DEVICE_NAME + "</li>"
        })

        var contentAfter = `</ul>
						</div>
					</div>
				</div>
			</div>`

        $("body").append(contentBefor + contentList + contentAfter);

        var tmid = window.setTimeout(function () {
            $("#rfidDevices").remove();
            success(devices[0])
        }, 6000)

        $('#rfidDevices .rfidList').click(function () {
            deviceIndex = $(this).data('index')
            $("#rfidDevices").remove();
            success(devices[deviceIndex])
            window.clearTimeout(tmid)
        })
    }

}

export default {
    zzNewRfid
}
